<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formType === 'view' ? {} : formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-form-item label="标签名称" prop="name">
        <el-input
          v-model="formData.name"
          placeholder="请输入标签名称"
          :disabled="formType === 'view'"
        />
      </el-form-item>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="开启状态" prop="status">
            <el-radio-group v-model="formData.status" :disabled="formType === 'view'">
              <el-radio
                v-for="dict in getIntDictOptions(DICT_TYPE.COMMON_STATUS)"
                :key="dict.value"
                :value="dict.value"
              >
                {{ dict.label }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="排序" prop="sort">
            <el-input-number
              v-model="formData.sort"
              placeholder="请输入排序"
              :disabled="formType === 'view'"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="关联客户" prop="customIds">
        <el-select
          v-model="formData.customIds"
          multiple
          filterable
          placeholder="请选择关联客户"
          class="!w-full"
          :disabled="formType === 'view'"
        >
          <el-option
            v-for="item in customerList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input
          v-model="formData.remark"
          placeholder="请输入备注"
          :disabled="formType === 'view'"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button
        v-if="formType !== 'view'"
        @click="submitForm"
        type="primary"
        :disabled="formLoading"
        >确 定</el-button
      >
      <el-button @click="dialogVisible = false">{{
        formType === 'view' ? '关 闭' : '取 消'
      }}</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { getIntDictOptions, DICT_TYPE } from '@/utils/dict'
import { CustomerTagApi, CustomerTagVO } from '@/api/erp/customer/tag'
import { CustomerApi, CustomerVO } from '@/api/erp/customer/customer'

/** ERP 客户标签 表单 */
defineOptions({ name: 'CustomerTagForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  name: undefined,
  remark: undefined,
  status: 0,
  sort: undefined,
  customIds: [] as number[] // 关联的客户ID列表
})
const formRules = reactive({
  name: [{ required: true, message: '标签名称不能为空', trigger: 'blur' }],
  status: [{ required: true, message: '开启状态不能为空', trigger: 'blur' }],
  sort: [{ required: true, message: '排序不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref
const customerList = ref<CustomerVO[]>([]) // 客户列表

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 加载所有客户列表
  formLoading.value = true
  try {
    // 获取所有客户列表
    customerList.value = await CustomerApi.getCustomerSimpleList()

    // 修改时，设置数据
    if (id) {
      const tagData = await CustomerTagApi.getCustomerTag(id)

      // 处理关联客户数据，确保正确回显
      // 情况1: 如果后端返回了customIds字符串，转换为数组
      if (tagData.customIds && typeof tagData.customIds === 'string') {
        tagData.customIds = tagData.customIds
          .split(',')
          .filter((id) => id)
          .map((id) => parseInt(id))
      }
      // 情况3: 如果customIds是数组但包含字符串元素，需要转换为数字
      else if (
        Array.isArray(tagData.customIds) &&
        tagData.customIds.length > 0 &&
        typeof tagData.customIds[0] === 'string'
      ) {
        tagData.customIds = tagData.customIds.filter((id) => id).map((id) => parseInt(id))
      }
      // 情况4: 确保customIds始终是数组类型
      if (!Array.isArray(tagData.customIds)) {
        tagData.customIds = []
      }

      formData.value = tagData
    }
  } finally {
    formLoading.value = false
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    // 克隆表单数据，避免修改原始数据
    const data = { ...formData.value } as unknown as CustomerTagVO

    // 将customIds数组转换为逗号分隔的字符串，无论是否为空数组
    // 确保customIds永远以字符串的方式提交
    if (data.customIds && Array.isArray(data.customIds)) {
      data.customIds = data.customIds.join(',')
    } else {
      // 如果customIds不是数组或未定义，设置为空字符串
      data.customIds = ''
    }

    if (formType.value === 'create') {
      await CustomerTagApi.createCustomerTag(data)
      message.success(t('common.createSuccess'))
    } else {
      await CustomerTagApi.updateCustomerTag(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    name: undefined,
    remark: undefined,
    status: 0,
    sort: undefined,
    customIds: []
  }
  customerList.value = []
  formRef.value?.resetFields()
}
</script>
